package com.rds.web.controller.system;

import com.rds.common.annotation.Log;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.RdaPowerControl;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.core.redis.RedisCache;
import com.rds.common.enums.BusinessType;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.spring.SpringUtils;
import com.rds.system.mapper.DocumentMapper;
import com.rds.system.service.IRdaPowerControlService;
import com.rds.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 权限管理信息
 *
 * @author rds
 */
@RestController
@RequestMapping("/system/authority")
public class RdaPowerControlController extends BaseController {

    @Autowired
    private IRdaPowerControlService powerControlService;
    @Autowired
    private DocumentMapper documentMapper;
    @Autowired
    private ISysRoleService roleService;

    /**
     * 权限管理添加属性
     */
    @PreAuthorize("@ss.hasPermi('system:authority:add')")
    @Log(title = "添加属性", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody RdaPowerControl rdapowercontrol){
        return toAjax(powerControlService.insertRdaPowerControl(rdapowercontrol));
    }

    /**
     * 权限管理保存更改修改表单
     */
    @PreAuthorize("@ss.hasPermi('system:authority:edit')")
    @PutMapping("/edit")
    @Transactional
    public AjaxResult edit(@RequestBody RdaPowerControl[] rdapowercontrol){
        int row=0;
        for(int i=0;i<rdapowercontrol.length;i++){
            RdaPowerControl pc=rdapowercontrol[i];
            RdaPowerControl rpc=new RdaPowerControl();
            rpc.setRead(pc.getRead());
            rpc.setModify(pc.getModify());
            rpc.setRemove(pc.getRemove());
            rpc.setCreated(pc.getCreated());
            rpc.setRelease(pc.getRelease());
            rpc.setRevise(pc.getRevise());
            rpc.setObsolete(pc.getObsolete());
            rpc.setViews(pc.getViews());
            rpc.setCheckIn(pc.getCheckIn());
            rpc.setDownload(pc.getDownload());
            rpc.setPromote(pc.getPromote());
            rpc.setDemote(pc.getDemote());
            rpc.setModifyTime(DateUtils.getNowDate());
            rpc.setModifyUserName(SecurityUtils.getUsername());
            rpc.setSubordinate(pc.getSubordinate());
            if(pc.getId()!=null){//有Id就更新，没Id就插入
                rpc.setId(pc.getId());
                rpc.setAttribute(pc.getAttribute());
                rpc.setAttributeValue(pc.getAttributeValue());
                row=powerControlService.updateRdaPowerControl(rpc);
            }else {
                if(pc.getAttribute()!=null && !pc.getAttribute().equals("") || pc.getAttributeValue()!=null && !pc.getAttributeValue().equals("")){//属性或属性值不为null的时候可以添加多条相同数据
                    rpc.setRoleId(pc.getRoleId());
                    rpc.setPolicyId(pc.getPolicyId());
                    rpc.setPolicyStateId(pc.getPolicyStateId());
                    rpc.setAttribute(pc.getAttribute());
                    rpc.setAttributeValue(pc.getAttributeValue());
                    row=powerControlService.insertRdaPowerControl(rpc);
                }else {
                    rpc.setRoleId(pc.getRoleId());
                    rpc.setPolicyId(pc.getPolicyId());
                    rpc.setPolicyStateId(pc.getPolicyStateId());
                    List<RdaPowerControl> list=powerControlService.selectRdaPowerControlListCount(rpc);
                    int count=i+1;
                    if(list.size()>=1){
                        return AjaxResult.error("未设置属性跟属性值无法添加相同角色数据，问题数据行"+count+"添加失败");
                    }
                    rpc.setAttribute(pc.getAttribute());
                    rpc.setAttributeValue(pc.getAttributeValue());
                    row=powerControlService.insertRdaPowerControl(rpc);
                }
            }
        }
        return toAjax(row);
    }

    /**
     * 查询根据策略查询
     */
    @PreAuthorize("@ss.hasPermi('system:authority:list')")
    @GetMapping("/list")
    public TableDataInfo list(String policyId, String policyStateId){
        startPage();
        RdaPowerControl rdapowercontrol=new RdaPowerControl();
        rdapowercontrol.setPolicyId(Long.valueOf(policyId));
        rdapowercontrol.setPolicyStateId(Long.valueOf(policyStateId));
        List<RdaPowerControl> list = powerControlService.selectRdaPowerControl(rdapowercontrol);
        return getDataTable(list);
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:authority:remove')")
    @DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(powerControlService.deleteRdaPowerControl(ids));
    }

    /**
     * 更新用户权限
     */
    @GetMapping("/updateCache")
    public AjaxResult updateCache() {
        Long userId= SecurityUtils.getUserId();
        Set<String> perms = new HashSet<String>();
        perms.addAll(roleService.selectRoleKeys(userId).get("roleSet"));
        if(perms.size()>0){
            //获取角色的数据权限
            List<RdaPowerControl> powerControls=powerControlService.selectPrivilegeId(perms);
            Map<String, Set<Long>> userPermission = new HashMap<>();
            List<String> readList = new ArrayList<>();
            Set<Long> readset=new HashSet<>(); Set<Long> modifyset=new HashSet<>();
            Set<Long> removeset=new HashSet<>();Set<Long> createdset=new HashSet<>();
            Set<Long> releaseset=new HashSet<>();Set<Long> reviseset=new HashSet<>();
            Set<Long> obsoleteset=new HashSet<>();Set<Long> viewsset=new HashSet<>();
            Set<Long> checkinset=new HashSet<>();Set<Long> downloadset=new HashSet<>();
            Set<Long> promoteset=new HashSet<>();Set<Long> demoteset=new HashSet<>();
            Set<Long> subordinateset=new HashSet<>();
            String read="";String modify="";String remove="";String created="";String release="";String revise="";String obsolete="";
            String views="";String checkin="";String download="";String promote="";String demote="";String subordinate="";
            for (RdaPowerControl privilege:powerControls){
                if(privilege.getRead()){
                    readset.add(privilege.getPolicyStateId());
                    readList.add(privilege.getPolicyStateId()+";"+privilege.getAttribute()+";"+privilege.getAttributeValue());
                    if(read.length()>0){
                        read = read +","+ privilege.getPolicyStateId();
                    }else{
                        read = read + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getModify()){
                    modifyset.add(privilege.getPolicyStateId());
                    if(modify.length()>0){
                        modify= modify +","+ privilege.getPolicyStateId();
                    }else{
                        modify= modify + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getRemove()){
                    removeset.add(privilege.getPolicyStateId());
                    if(remove.length()>0){
                        remove= remove +","+ privilege.getPolicyStateId();
                    }else{
                        remove= remove + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getCreated()){
                    createdset.add(privilege.getPolicyStateId());
                    if(created.length()>0){
                        created= created +","+ privilege.getPolicyStateId();
                    }else{
                        created= created + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getRelease()){
                    releaseset.add(privilege.getPolicyStateId());
                    if(release.length()>0){
                        release= release +","+ privilege.getPolicyStateId();
                    }else{
                        release= release + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getRevise()){
                    reviseset.add(privilege.getPolicyStateId());
                    if(revise.length()>0){
                        revise= revise +","+ privilege.getPolicyStateId();
                    }else{
                        revise= revise + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getObsolete()){
                    obsoleteset.add(privilege.getPolicyStateId());
                    if(obsolete.length()>0){
                        obsolete= obsolete +","+ privilege.getPolicyStateId();
                    }else{
                        obsolete= obsolete + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getViews()){
                    viewsset.add(privilege.getPolicyStateId());
                    if(views.length()>0){
                        views= views +","+ privilege.getPolicyStateId();
                    }else{
                        views= views + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getCheckIn()){
                    checkinset.add(privilege.getPolicyStateId());
                    if(checkin.length()>0){
                        checkin= checkin +","+ privilege.getPolicyStateId();
                    }else{
                        checkin= checkin + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getDownload()){
                    downloadset.add(privilege.getPolicyStateId());
                    if(download.length()>0){
                        download= download +","+ privilege.getPolicyStateId();
                    }else{
                        download= download + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getPromote()){
                    promoteset.add(privilege.getPolicyStateId());
                    if(promote.length()>0){
                        promote= promote +","+ privilege.getPolicyStateId();
                    }else{
                        promote= promote + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getDemote()){
                    demoteset.add(privilege.getPolicyStateId());
                    if(demote.length()>0){
                        demote= demote +","+ privilege.getPolicyStateId();
                    }else{
                        demote= demote + privilege.getPolicyStateId();
                    }
                }
                if(privilege.getSubordinate()){
                    subordinateset.add(privilege.getPolicyStateId());
                    if(subordinate.length()>0){
                        subordinate= subordinate +","+ privilege.getPolicyStateId();
                    }else{
                        subordinate= subordinate + privilege.getPolicyStateId();
                    }
                }
            }
            //缓存角色的数据权限
            userPermission.put("read",readset);
            userPermission.put("modify",modifyset);
            userPermission.put("remove",removeset);
            userPermission.put("created",createdset);
            userPermission.put("release",releaseset);
            userPermission.put("revise",reviseset);
            userPermission.put("obsolete",obsoleteset);
            userPermission.put("views",viewsset);
            userPermission.put("checkin",checkinset);
            userPermission.put("download",downloadset);
            userPermission.put("promote",promoteset);
            userPermission.put("demote",demoteset);
            userPermission.put("subordinate",subordinateset);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-read", read);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-modify", modify);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-remove", remove);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-created", created);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-release", release);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-revise", revise);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-obsolete", obsolete);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-views", views);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-checkin", checkin);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-download", download);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-promote", promote);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-demote", demote);
            SpringUtils.getBean(RedisCache.class).setCacheObject(userId+"-subordinate", subordinate);

            SpringUtils.getBean(RedisCache.class).deleteObject(userId+"-readList");
            SpringUtils.getBean(RedisCache.class).setCacheList(userId+"-readList", readList);

            SpringUtils.getBean(RedisCache.class).setCacheMap(userId+"userPermission", userPermission);
            System.out.println("=====================================缓存用户的数据权限");
        }
        return toAjax(1);
    }

    /**
     * 判断当前用户是否有操作权限
     */
    @GetMapping("/permissions")
    public int permissions(String operateType,String state) {
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            return 1;
        }else{
            String key = SecurityUtils.getUserId()+"-"+operateType;
            String stateStr= SpringUtils.getBean(RedisCache.class).getCacheObject(key);
            if(stateStr!=null && !stateStr.equals("")){
                if(stateStr.contains(state)){
                    return 1;
                }else{
                    return 0;
                }
            }else{
                return 0;
            }
        }
    }

    /**
     * 判断当前用户是否有操作权限
     */
    @GetMapping("/permissionsNoState")
    public int permissionsNoState(String operateType,String docId) {
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            return 1;
        }else{
            String key = SecurityUtils.getUserId()+"-"+operateType;
            String stateStr= SpringUtils.getBean(RedisCache.class).getCacheObject(key);
            if(stateStr!=null && !stateStr.equals("")){
                String stateId = String.valueOf(documentMapper.selectDocumentById(Long.valueOf(docId)).getStateid());
                if(stateStr.contains(stateId)){
                    return 1;
                }else{
                    return 0;
                }
            }else{
                return 0;
            }
        }
    }
}
